<?php
/**
 * Created by PhpStorm.
 * User: jungshen
 * Date: 2018/11/14
 * Time: 14:12
 */

namespace app\api\middleware;
use service\HttpService;
use think\Exception;
use think\facade\Config;
use think\facade\Cookie;
use think\Request;


/**
 * 文本审核中间件
 * Class TextAudit
 * @package app\api\middleware
 */
class TextAudit
{
    /**
     * @param Request $request
     * @param \Closure $next
     * @return mixed
     * @throws Exception
     */
    public function handle($request,\Closure $next)
    {
        $fields=['title','content'];
        foreach ($fields as $field){
            if(trim($request->param($field,''))!=''){
                //执行文本审核
                $accessToken=$this->get_access_token();
                $param=[
                    'access_token'=>$accessToken,
                    'content'=>$request->param($field)
                ];
                $json=HttpService::post(Config::get('bce.TextCensoringUrl'),$param);
                $res=json_decode($json,true);
                if(isset($res['result'])){
                    $result=$res['result'];
                    if($result['spam']==1){
                        //违禁
                        $reject=$result['reject'];
                        $hits=[];
                        foreach ($reject as $v){
                            $hits=array_merge($v['hit'],$hits);
                        }
                        if(count($hits)>0){
                            //拒绝通过
                            throw new Exception('您发布的内容含有敏感词',403);
                        }else{
                            //人工审核
                            $request->status=1;
                        }
                    }elseif($result['spam']==2){
                        //建议人工审核
                        $request->status=1;
                    }else{
                        $request->status=1;
                    }
                }
            }
        }

        return $next($request);
    }

    /**
     * 获取bce_access_token
     * @return mixed
     * @throws Exception
     */
    private function get_access_token(){
        if(Cookie::get('bce_access_token')){
            return Cookie::get('bce_access_token');
        }else{
            $param=[
                'grant_type'=>'client_credentials',
                'client_id'=>Config::get('bce.AccessKey'),
                'client_secret'=>Config::get('bce.SecretKey'),
            ];
            $json=HttpService::post(Config::get('bce.AccessTokenUrl'),$param);
            $arr=json_decode($json,true);
            if(isset($arr['access_token'])){
                //获取成功
                Cookie::set('bce_access_token',$arr['access_token'],$arr['expires_in']);
                return $arr['access_token'];
            }else{
                throw new Exception($arr['error'].':'.$arr['error_description']);
            }

        }
    }
}